<template>
  <div class="app-container">
    <el-form :model="queryForm" ref="queryFormRef" :inline="true">
      <el-form-item prop="deptName" label="部门名称">
        <el-input v-model="queryForm.deptName" placeholder="请输入部门名称" @press-enter="handleQuery" />
      </el-form-item>
      <el-form-item prop="status" label="部门状态">
        <el-select v-model="queryForm.status" placeholder="请选择部门状态">
          <el-option :value="2">正常</el-option>
          <el-option :value="1">停用</el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-space>
          <el-button v-has="'admin:sysDept:query'" type="primary" @click="handleQuery" icon="Search"> 搜索</el-button>
          <el-button @click="handleResetQuery" icon="Refresh">重置</el-button>
        </el-space>
      </el-form-item>
    </el-form>

    <el-divider />

    <div class="action">
      <el-button v-has="'admin:sysDept:add'" type="primary" @click="handleAdd()" icon="Plus"> 新增</el-button>
    </div>

    <!-- 异步数据需要defualt-expanded-keys 传入所有行Key才能默认展开 -->
    <el-table :data="tableData" row-key="deptId" table-layout="auto">
      <el-table-column label='部门名称' prop='deptName'></el-table-column>
      <el-table-column label='排序' prop='sort'></el-table-column>
      <el-table-column label='状态' prop='status'>
        <template #default="scope">
          <el-tag v-if="scope.row.status == 2" type="success">正常</el-tag>
          <el-tag v-else type="danger">停用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label='创建时间' prop='createdAt'>
        <template #default="scope">
          {{ parseTime(scope.row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column label='操作' prop='action'>
        <template #default="scope">
          <el-button v-has="'admin:sysDept:edit'" text type="primary" @click="handleUpdate(scope.row)" icon="Edit">
            修改</el-button>
          <el-button v-has="'admin:sysDept:add'" text type="primary" @click="handleAdd(scope.row)" icon="Plus">
            新增</el-button>
          <el-button v-has="'admin:sysDept:remove'" text type="primary"
            @click="() => { deleteVisible = true; deleteData = [scope.row.deptId];  }" icon="Delete"> 删除</el-button>
        </template>
      </el-table-column>
    </el-table>



    <!-- Modal -->
    <el-dialog v-model="modalVisible" :title="modalTitle" title-align="start" @before-ok="handleBeforeOk"
      @close="() => modalFormRef.resetFields()">
      <el-form :model="modalForm" :rules="rules" ref="modalFormRef">
        <el-form-item prop="parentId" label="上级部门">
          <el-tree-select v-model="modalForm.parentId" :data="tableData"
            :props="{ key: 'deptId', label: 'deptName',value:'deptId' }" placeholder="请选择上级部门" allow-clear />
        </el-form-item>
        <el-form-item prop="deptName" label="部门名称">
          <el-input v-model="modalForm.deptName" placeholder="请输入部门名称" />
        </el-form-item>
        <el-form-item prop="leader" label="负责人">
          <el-input v-model="modalForm.leader" placeholder="请输入负责人" />
        </el-form-item>
        <el-form-item prop="phone" label="联系电话">
          <el-input v-model="modalForm.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item prop="email" label="邮箱">
          <el-input v-model="modalForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item prop="status" label="部门状态">
          <el-radio-group v-model="modalForm.status">
            <el-radio :label="2">正常</el-radio>
            <el-radio :label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span>
          <el-button @click="modalFormRef.resetFields();modalVisible = false">取消</el-button>
          <el-button @click="handleBeforeOk" type="primary">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- Akiraka 20230223 删除与批量删除 开始 -->
    <DeleteModal :data="deleteData" :visible="deleteVisible" :apiDelete="removeDept"
      @deleteVisibleChange="() => deleteVisible = false" />
    <!-- Akiraka 20230223 删除与批量删除 结束 -->
  </div>
</template>

<script setup>
import { reactive, ref, onMounted, getCurrentInstance, nextTick, watch } from 'vue';
import { getDept, addDept, removeDept, updateDept } from '@/api/admin/sys-dept';
import {parseTime} from '@/utils/parseTime'
import Status from '@/components/Fields/State.vue'

const queryFormRef = ref({});
const modalFormRef = ref({});
// Akiraka 20230210 删除数据
const deleteData = ref([])
// Akiraka 20230210 删除对话框
const deleteVisible = ref(false)
// Akiraka 20230210 监听删除事件
watch(() => deleteVisible.value ,(value) => {
  if ( value == false ) {
    getDeptInfo(queryForm);
  }
})

const { proxy } = getCurrentInstance();

// Modal
const modalVisible = ref(false);
const modalTitle = ref('默认标题');

// Form
const queryForm = reactive({});
const modalForm = reactive({
  status: 2,
});

// rules
const rules = {
  parentId: [{ required: true, message: '请选择上级部门' }],
  deptName: [{ required: true, message: '请输入部门名称' }],
  leader: [{ required: true, message: '请输入负责人' }],
};

// Columns
const columns = [
  {title: '部门名称',dataIndex: 'deptName',},
  {title: '排序',dataIndex: 'sort',},
  {title: '状态',dataIndex: 'status',slotName: 'status',},
  {title: '创建时间',dataIndex: 'createdAt',slotName: 'createdAt',},
  {title: '操作',slotName: 'action',},
];

// Table Data
const tableData = ref([]);

// 查询
const handleQuery = async () => {
  const res = await getDept(queryForm);
  tableData.value = deepDelChildren(res.data);
};

// 重置查询
const handleResetQuery = () => {
  queryFormRef.value.resetFields();

  getDeptInfo(queryForm);
}

// 新增
const handleAdd = ({ deptId, status = 2 } = {}) => {
  modalVisible.value = true;
  modalTitle.value = '新增部门';

  if (deptId) Object.assign(modalForm, {parentId: deptId, status});
};

// 修改
const handleUpdate = async (record) => {
  modalVisible.value = true;
  modalTitle.value = '修改部门信息';

  await nextTick();
  const { parentId, deptName, leader, phone, email, status, deptId } = record;
  Object.assign(modalForm, {
    parentId,
    deptName,
    leader,
    phone,
    email,
    status,
    deptId,
  });
};

// 递归删除空Children
function deepDelChildren(data) {
  const depts = data;
  let len = depts?.length;
  // let len = depts && depts.length;

  for (let i = 0; i < len; i++) {
    if (depts[i].children.length > 0) {
      deepDelChildren(depts[i].children);
    } else {
      delete depts[i].children;
    }
  }

  return depts;
}

// Modal 表单提交前检查
const handleBeforeOk = (done) => {
  modalFormRef.value.validate(async (err) => {
    if (!err) {
      let res;
      if (Reflect.has(modalForm, 'deptId')) {
        const { code, msg } = await updateDept(modalForm, modalForm.deptId);
        if (code == 200 ) {
          proxy.$message.success('修改成功');
        } else {
          proxy.$message.error(msg);
        }
      } else {
        const { code, msg } = await addDept(modalForm);
        if (code == 200 ) {
          proxy.$message.success('新增成功');
        } else {
          proxy.$message.error(msg);
        }
      }
      done();
      getDeptInfo();
    } else {
      proxy.$message.error('数据校验失败');
      done(false);
    }
  });
};

// 获取部门信息
const getDeptInfo = async (params = {}) => {
  const { data, code, msg } = await getDept(params);
  if ( code == 200 ) {
    tableData.value = deepDelChildren(data);
  } else {
    proxy.$message.error(msg);
  }
};

onMounted(async () => {
  getDeptInfo();
});
</script>

<style lang="scss">
.action {
  margin-bottom: 8px;
}
</style>
